import subprocess
import sys
import os
import up2

def get_video_duration(video_path):
    """使用 ffprobe 获取视频总时长（秒）"""
    cmd = [
        './ffmpeg/ffprobe',
        '-v', 'error',
        '-show_entries', 'format=duration',
        '-of', 'csv=p=0',
        video_path
    ]
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    if result.returncode != 0:
        raise RuntimeError(f"ffprobe error: {result.stderr}")
    try:
        duration = float(result.stdout.strip())
        return duration
    except ValueError:
        raise RuntimeError("无法解析视频时长")

def split_video(input_file, n_segments):
    # 获取视频总时长
    total_duration = get_video_duration(input_file)
    segment_duration = total_duration / n_segments

    # 使用 awk 计算每个片段的 start 和 duration（避免 Python 浮点精度问题影响 ffmpeg）
    # 这里我们用 awk 来生成每个片段的参数
    awk_script = f'''
    BEGIN {{
        total = {total_duration};
        n = {n_segments};
        seg_dur = total / n;
        for (i = 0; i < n; i++) {{
            start = i * seg_dur;
            printf "%.6f %.6f\\n", start, seg_dur;
        }}
    }}
    '''

    # 调用 awk
    awk_cmd = ['awk', awk_script]
    result = subprocess.run(awk_cmd, stdout=subprocess.PIPE, text=True)
    if result.returncode != 0:
        raise RuntimeError("awk 执行失败")

    # 解析 awk 输出
    lines = result.stdout.strip().split('\n')
    base_name = os.path.splitext(input_file)[0]

    for idx, line in enumerate(lines):
        if not line.strip():
            continue
        start_str, duration_str = line.split()
        start = float(start_str)
        duration = float(duration_str)

        output_file = f"{base_name}_part_{idx+1:03d}.mp4"

        print(f"正在生成片段 {idx+1}/{n_segments}: {output_file} (start={start:.3f}, duration={duration:.3f})")

        ffmpeg_cmd = [
            './ffmpeg/ffmpeg',
            '-y',  # 自动覆盖输出文件
            '-ss', str(start),
            '-i', input_file,
            '-t', str(duration),
            '-c:v', 'copy',
            '-c:a', 'copy',
            '-avoid_negative_ts', 'make_zero',
            '-reset_timestamps', '1',  # 可选：让每个片段从0开始时间戳
            output_file
        ]

        # 执行 ffmpeg 命令
        proc = subprocess.run(ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if proc.returncode != 0:
            print(f"❌ 分割失败: {output_file}")
            print(proc.stderr.decode('utf-8'))
        else:
            print(f"✅ 成功生成: {output_file}")
            up2.uploadfile(output_file)

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("用法: python split_video.py <视频文件路径> <分割段数>")
        sys.exit(1)

    video_file = sys.argv[1]
    try:
        n = int(sys.argv[2])
    except ValueError:
        print("错误：段数必须是整数")
        sys.exit(1)

    if not os.path.isfile(video_file):
        print(f"错误：文件不存在: {video_file}")
        sys.exit(1)

    if n < 1:
        print("错误：段数必须大于0")
        sys.exit(1)

    split_video(video_file, n)
